const oldArrayMethods = Array.prototype;
const arrayMethods = Object.create(oldArrayMethods);
const methods = [
  "push",
  "shift",
  "unshift",
  "pop",
  "sort",
  "splice",
  "reverse",
];
methods.forEach((method) => {
  arrayMethods[method] = function(...args) {
    console.log("监听修改");
    return oldArrayMethods[method].apply(this, args);
  };
});
function defineReactive(target, key, value) {
  observer(value); // 递归调用
  Object.defineProperty(target, key, {
    get() {
      console.log("get", key, value);
      return value;
    },
    set(newValue) {
      if (newValue !== value) {
        console.log("set", key, value);
        observer(newValue); // 新属性添加get set
        value = newValue;
      }
    },
  });
}
function observer(target) {
  if (typeof target !== "object" || target === null) {
    return target;
  }
  if (Array.isArray(target)) {
    target.__proto__ = arrayMethods;
  }
  for (const key in target) {
    defineReactive(target, key, target[key]);
  }
}
